﻿namespace Atomic.Modules.Security
{
    using System;
    using System.Linq;
    using System.Collections.Generic;

    using Atomic.Domain;

    /// <summary>
    /// 角色信息。
    /// </summary>
    public class Role : EntityBase
    {
        /// <summary>
        /// 名称。
        /// </summary>
        private string _name = string.Empty;

        /// <summary>
        /// 显示名称。
        /// </summary>
        private string _displayName = string.Empty;

        /// <summary>
        /// 名称。
        /// </summary>
        public string Name
        {
            get
            {
                return this._name;
            }
            set
            {
                string name = value;

                if (string.IsNullOrWhiteSpace(name))
                {
                    throw new ArgumentNullException("name", "角色名不可以是空的。");
                }

                if (!UserValidator.Current.IsChar(name))
                {
                    throw new ArgumentException("name", "角色名只可以是字符。");
                }

                this._name = name;
            }
        }

        /// <summary>
        /// 显示名称。
        /// </summary>
        public string DisplayName
        {
            get
            {
                return this._displayName;
            }
            set
            {
                string displayName = value;

                if (string.IsNullOrWhiteSpace(displayName))
                {
                    throw new ArgumentNullException("displayName", "角色显示名称不可以是空的。");
                }

                if (!UserValidator.Current.IsChar(displayName))
                {
                    throw new ArgumentException("displayName", "角色显示名称只可以是字符。");
                }

                this._displayName = displayName;
            }
        }

        /// <summary>
        /// 角色类型。
        /// </summary>
        public RoleType Type { get; set; }

        /// <summary>
        /// 权限集合。
        /// </summary>
        public IEnumerable<Permission> Permissions { get; private set; }

        /// <summary>
        /// 判断当前角色是否拥有指定权限。
        /// </summary>
        /// <param name="permissionId"></param>
        /// <returns></returns>
        public bool IsAuthorize(int permissionId)
        {
            return this.Permissions.Any(permission => permission.Id == permissionId);
        }

        /// <summary>
        /// 判断当前角色是否拥有指定权限。
        /// </summary>
        /// <param name="permission"></param>
        /// <returns></returns>
        public bool IsAuthorize(Permission permission)
        {
            return this.Permissions.Any(p => p.Id == permission.Id);
        }

        /// <summary>
        /// 设置角色拥有的权限。
        /// </summary>
        /// <param name="permissions">权限集合。</param>
        public void SetPermissions(IEnumerable<Permission> permissions)
        {
            this.Permissions = permissions;
        }
    }
}